package com.yx.frame.builder.code;

import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.net.URL;

import com.yx.frame.builder.validate.ServiceBuilderConfigManager;

public class JavaClientCode {
	String rootPath;
	String jsFileName;
	String jsControlName;
	OutputStreamWriter jsWriter = null;
	String host;
	int port;
	public JavaClientCode(String rootPath, String jsFileName, String jsControlName) throws Exception {
		this.rootPath = rootPath;
		this.jsFileName = jsFileName;
		this.jsControlName = jsControlName;
		File path = new File(rootPath + "/client/java/");
		if (!path.exists()) {
			path.mkdirs();
		}
		String jsFilePath = rootPath + "/client/java/" + jsControlName + ".java";
		File file = new File(jsFilePath);
		if (file.exists()) {
			file.delete();
		}
		String serverUrl=ServiceBuilderConfigManager.getInstance().getServerUrl();
		URL aURL = new URL(serverUrl);
		host = aURL.getHost();
		port = aURL.getPort();
		jsWriter = new OutputStreamWriter(new FileOutputStream(file), "UTF-8");
	}

	public void writeHead() throws Exception {
		jsWriter.write("package client.java;\r\n");
		jsWriter.write("\r\n");
		jsWriter.write("import java.io.BufferedReader;\r\n");
		jsWriter.write("import java.io.File;\r\n");
		jsWriter.write("import java.io.FileInputStream;\r\n");
		jsWriter.write("import java.io.IOException;\r\n");
		jsWriter.write("import java.io.InputStream;\r\n");
		jsWriter.write("import java.io.InputStreamReader;\r\n");
		jsWriter.write("import java.io.PrintWriter;\r\n");
		jsWriter.write("import java.net.HttpURLConnection;\r\n");
		jsWriter.write("import java.net.InetSocketAddress;\r\n");
		jsWriter.write("import java.net.URL;\r\n");
		jsWriter.write("import java.net.URLConnection;\r\n");
		jsWriter.write("import java.net.URLEncoder;\r\n");
		jsWriter.write("import java.nio.ByteBuffer;\r\n");
		jsWriter.write("import java.nio.CharBuffer;\r\n");
		jsWriter.write("import java.nio.channels.FileChannel;\r\n");
		jsWriter.write("import java.nio.channels.SocketChannel;\r\n");
		jsWriter.write("import java.nio.charset.Charset;\r\n");
		jsWriter.write("import java.nio.charset.CharsetDecoder;\r\n");
		jsWriter.write("import java.security.MessageDigest;\r\n");
		jsWriter.write("import java.util.ArrayList;\r\n");
		jsWriter.write("import java.util.List;\r\n");
		jsWriter.write("\r\n");
		jsWriter.write("import javax.crypto.Cipher;\r\n");
		jsWriter.write("import javax.crypto.spec.IvParameterSpec;\r\n");
		jsWriter.write("import javax.crypto.spec.SecretKeySpec;\r\n");
		jsWriter.write("\r\n");
		jsWriter.write("import org.json.JSONArray;\r\n");
		jsWriter.write("import org.json.JSONObject;\r\n");
		jsWriter.write("\r\n");
		jsWriter.write("public final class "+jsControlName+" {\r\n");
		jsWriter.write("	private static final String _pKey = \"ShhOt0m5gfMpsLjP\";\r\n");
		jsWriter.write("	private static final SFC _instence=new SFC();\r\n");
		jsWriter.write("	private static char[] base64EncodeChars = new char[] { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L',\r\n");
		jsWriter.write("			'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g',\r\n");
		jsWriter.write("			'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1',\r\n");
		jsWriter.write("			'2', '3', '4', '5', '6', '7', '8', '9', '+', '/' };\r\n");
		jsWriter.write("	private static final String BOUNDARY = \"----WebKitFormBoundaryT1HoybnYeFOGFlBR\";\r\n");
		jsWriter.write("	private static final Charset charset = Charset.forName(\"UTF8\");\r\n");
		jsWriter.write("	private static String _host = \""+host+"\";\r\n");
		jsWriter.write("	private static int _port = "+port+";\r\n");
		jsWriter.write("	private static String _Uid = \"wukai\";\r\n");
		jsWriter.write("	private static String _webServer = \"\";\r\n");
		jsWriter.write("\r\n");
		jsWriter.write("	private final static String getUID(){\r\n");
		jsWriter.write("		return _Uid;\r\n");
		jsWriter.write("	}\r\n");
		jsWriter.write("	public final static void setUID(String uid){\r\n");
		jsWriter.write("		_Uid=uid;\r\n");
		jsWriter.write("	}\r\n");
		jsWriter.write("	public final static String setUser(String userName, String password) throws Exception {\r\n");
		jsWriter.write("		long timestamp = System.currentTimeMillis();\r\n");
		jsWriter.write("		String md5Key = MD5(password + timestamp);\r\n");
		jsWriter.write("		if (md5Key.length() > 16)\r\n");
		jsWriter.write("			md5Key = md5Key.substring(0, 16);\r\n");
		jsWriter.write("		String encrypted = AESEncrypt(String.valueOf(timestamp), md5Key);\r\n");
		jsWriter.write("		String signTxt = \"[\\\"\" + userName + \"\\\",\\\"\" + encrypted + \"\\\",\\\"\" + timestamp + \"\\\"]\";\r\n");
		jsWriter.write("		String signEncrypted = AESEncrypt(signTxt, _pKey);\r\n");
		jsWriter.write("		_Uid=signEncrypted;\r\n");
		jsWriter.write("		return getUID();\r\n");
		jsWriter.write("	}\r\n");
		jsWriter.write("\r\n");
		jsWriter.write("	private static String MD5(String str) throws Exception {\r\n");
		jsWriter.write("		String encode = str;\r\n");
		jsWriter.write("		StringBuilder stringbuilder = new StringBuilder();\r\n");
		jsWriter.write("		MessageDigest md5 = MessageDigest.getInstance(\"MD5\");\r\n");
		jsWriter.write("		md5.update(encode.getBytes(\"utf-8\"));\r\n");
		jsWriter.write("		byte[] str_encoded = md5.digest();\r\n");
		jsWriter.write("		for (int i = 0; i < str_encoded.length; i++) {\r\n");
		jsWriter.write("			if ((str_encoded[i] & 0xff) < 0x10) {\r\n");
		jsWriter.write("				stringbuilder.append(\"0\");\r\n");
		jsWriter.write("			}\r\n");
		jsWriter.write("			stringbuilder.append(Long.toString(str_encoded[i] & 0xff, 16));\r\n");
		jsWriter.write("		}\r\n");
		jsWriter.write("		return stringbuilder.toString();\r\n");
		jsWriter.write("	}\r\n");
		jsWriter.write("\r\n");
		jsWriter.write("	private static String AESEncrypt(String sSrc, String sKey) throws Exception {\r\n");
		jsWriter.write("		if (sKey == null)\r\n");
		jsWriter.write("			return null;\r\n");
		jsWriter.write("		if (sKey.length() != 16)\r\n");
		jsWriter.write("			return null;\r\n");
		jsWriter.write("		byte[] raw = sKey.getBytes();\r\n");
		jsWriter.write("		SecretKeySpec skeySpec = new SecretKeySpec(raw, \"AES\");\r\n");
		jsWriter.write("		Cipher cipher = Cipher.getInstance(\"AES/CBC/PKCS5Padding\");\r\n");
		jsWriter.write("		IvParameterSpec iv = new IvParameterSpec(sKey.getBytes());\r\n");
		jsWriter.write("		cipher.init(Cipher.ENCRYPT_MODE, skeySpec, iv);\r\n");
		jsWriter.write("		byte[] encrypted = cipher.doFinal(sSrc.getBytes());\r\n");
		jsWriter.write("		return encode(encrypted);\r\n");
		jsWriter.write("	}\r\n");
		jsWriter.write("\r\n");
		jsWriter.write("	private static String encode(byte[] data) {\r\n");
		jsWriter.write("		StringBuffer sb = new StringBuffer();\r\n");
		jsWriter.write("		int len = data.length;\r\n");
		jsWriter.write("		int i = 0;\r\n");
		jsWriter.write("		int b1, b2, b3;\r\n");
		jsWriter.write("		while (i < len) {\r\n");
		jsWriter.write("			b1 = data[i++] & 0xff;\r\n");
		jsWriter.write("			if (i == len) {\r\n");
		jsWriter.write("				sb.append(base64EncodeChars[b1 >>> 2]);\r\n");
		jsWriter.write("				sb.append(base64EncodeChars[(b1 & 0x3) << 4]);\r\n");
		jsWriter.write("				sb.append(\"==\");\r\n");
		jsWriter.write("				break;\r\n");
		jsWriter.write("			}\r\n");
		jsWriter.write("			b2 = data[i++] & 0xff;\r\n");
		jsWriter.write("			if (i == len) {\r\n");
		jsWriter.write("				sb.append(base64EncodeChars[b1 >>> 2]);\r\n");
		jsWriter.write("				sb.append(base64EncodeChars[((b1 & 0x03) << 4) | ((b2 & 0xf0) >>> 4)]);\r\n");
		jsWriter.write("				sb.append(base64EncodeChars[(b2 & 0x0f) << 2]);\r\n");
		jsWriter.write("				sb.append(\"=\");\r\n");
		jsWriter.write("				break;\r\n");
		jsWriter.write("			}\r\n");
		jsWriter.write("			b3 = data[i++] & 0xff;\r\n");
		jsWriter.write("			sb.append(base64EncodeChars[b1 >>> 2]);\r\n");
		jsWriter.write("			sb.append(base64EncodeChars[((b1 & 0x03) << 4) | ((b2 & 0xf0) >>> 4)]);\r\n");
		jsWriter.write("			sb.append(base64EncodeChars[((b2 & 0x0f) << 2) | ((b3 & 0xc0) >>> 6)]);\r\n");
		jsWriter.write("			sb.append(base64EncodeChars[b3 & 0x3f]);\r\n");
		jsWriter.write("		}\r\n");
		jsWriter.write("		return sb.toString();\r\n");
		jsWriter.write("	}\r\n");
		jsWriter.write("\r\n");
		jsWriter.write("	public final static InputStream fileDownload(String fileName)throws Exception {\r\n");
		jsWriter.write("		URL myFileURL;\r\n");
		jsWriter.write("		String url=\"http://\"+_host+\":\"+_port+_webServer+\"/Download?UId=\"+URLEncoder.encode(getUID(), \"UTF-8\")+\"&File=\"+URLEncoder.encode(URLEncoder.encode(fileName, \"UTF-8\"), \"UTF-8\");\r\n");
		jsWriter.write("        myFileURL = new URL(url);  \r\n");
		jsWriter.write("        HttpURLConnection conn=(HttpURLConnection)myFileURL.openConnection();  \r\n");
		jsWriter.write("        conn.setConnectTimeout(6000);\r\n");
		jsWriter.write("        conn.setDoInput(true); \r\n");
		jsWriter.write("        conn.setUseCaches(false); \r\n");
		jsWriter.write("        return conn.getInputStream();\r\n");
		jsWriter.write("	}\r\n");
		jsWriter.write("\r\n");
		jsWriter.write("	public final static String fileUpload(File file) throws Exception {\r\n");
		jsWriter.write("		FileInputStream fis = null;\r\n");
		jsWriter.write("		FileChannel fileChannel = null;\r\n");
		jsWriter.write("		SocketChannel channel = null;\r\n");
		jsWriter.write("		try {\r\n");
		jsWriter.write("			StringBuilder sb = new StringBuilder();\r\n");
		jsWriter.write("			sb.append(\"--\" + BOUNDARY + \"\\r\\n\");\r\n");
		jsWriter.write("			sb.append(\"Content-Disposition: form-data; name=\\\"UId\\\"\\r\\n\");\r\n");
		jsWriter.write("			sb.append(\"\\r\\n\");\r\n");
		jsWriter.write("			sb.append(getUID() + \"\\r\\n\");\r\n");
		jsWriter.write("			sb.append(\"--\" + BOUNDARY + \"\\r\\n\");\r\n");
		jsWriter.write("			sb.append(\"Content-Disposition: form-data; name=\\\"file1\\\"; filename=\\\"\" + file.getName() + \"\\\"\" + \"\\r\\n\");\r\n");
		jsWriter.write("			sb.append(\"Content-Type: image/jpeg\" + \"\\r\\n\");\r\n");
		jsWriter.write("			sb.append(\"\\r\\n\");\r\n");
		jsWriter.write("			String headerInfo = sb.toString();\r\n");
		jsWriter.write("			String endInfo = \"\\r\\n--\" + BOUNDARY + \"--\\r\\n\";\r\n");
		jsWriter.write("			channel = SocketChannel.open(new InetSocketAddress(_host, _port));\r\n");
		jsWriter.write("			StringBuffer request = new StringBuffer();\r\n");
		jsWriter.write("			request.append(\"POST \"+_webServer+\"/FileUpload HTTP/1.1\\r\\n\");\r\n");
		jsWriter.write("			request.append(\"Cache-Control: no-cache\\r\\n\");\r\n");
		jsWriter.write("			request.append(\"Pragma: no-cache\\r\\n\");\r\n");
		jsWriter.write("			request.append(\"User-Agent: JavaSocket/\").append(System.getProperty(\"java.version\")).append(\"\\r\\n\");\r\n");
		jsWriter.write("			request.append(\"Host: \").append(_host).append(\"\\r\\n\");\r\n");
		jsWriter.write("			request.append(\"Accept: text/html, image/gif, image/jpeg, *; q=.2, */*; q=.2\\r\\n\");\r\n");
		jsWriter.write("			request.append(\"Connection: keep-alive\\r\\n\");\r\n");
		jsWriter.write("			request.append(\"Content-Type: multipart/form-data; boundary=\" + BOUNDARY + \"\\r\\n\");\r\n");
		jsWriter.write("			request.append(\"Content-Length: \"\r\n");
		jsWriter.write("					+ (headerInfo.getBytes().length + file.length() + endInfo.getBytes().length) + \"\\r\\n\");\r\n");
		jsWriter.write("			request.append(\"\\r\\n\");\r\n");
		jsWriter.write("			channel.write(charset.encode(request.toString()));\r\n");
		jsWriter.write("			channel.write(charset.encode(headerInfo));\r\n");
		jsWriter.write("			fis = new FileInputStream(file);\r\n");
		jsWriter.write("			fileChannel = fis.getChannel();\r\n");
		jsWriter.write("			ByteBuffer buffer = ByteBuffer.allocate(1024);\r\n");
		jsWriter.write("			while (fileChannel.read(buffer) != -1) {\r\n");
		jsWriter.write("				buffer.flip();\r\n");
		jsWriter.write("				channel.write(buffer);\r\n");
		jsWriter.write("				buffer.clear();\r\n");
		jsWriter.write("			}\r\n");
		jsWriter.write("			channel.write(charset.encode(endInfo));\r\n");
		jsWriter.write("			channel.socket().shutdownOutput();\r\n");
		jsWriter.write("			int size = -1;\r\n");
		jsWriter.write("			buffer.clear();\r\n");
		jsWriter.write("			CharsetDecoder decoder = charset.newDecoder();\r\n");
		jsWriter.write("			StringBuffer retStr = new StringBuffer();\r\n");
		jsWriter.write("			while ((size = channel.read(buffer)) != -1) {\r\n");
		jsWriter.write("				buffer.flip();\r\n");
		jsWriter.write("				CharBuffer charBuffer = decoder.decode(buffer.asReadOnlyBuffer());\r\n");
		jsWriter.write("				retStr.append(charBuffer.toString());\r\n");
		jsWriter.write("				buffer.clear();\r\n");
		jsWriter.write("			}\r\n");
		jsWriter.write("			String jsonRetStr = retStr.toString();\r\n");
		jsWriter.write("			jsonRetStr = jsonRetStr.substring(jsonRetStr.indexOf(\"{\"), jsonRetStr.length() - 9);\r\n");
		jsWriter.write("			JSONObject returnObj = new JSONObject(jsonRetStr);\r\n");
		jsWriter.write("			if (!returnObj.getBoolean(\"IsOK\")) {\r\n");
		jsWriter.write("				throw new Exception(returnObj.getString(\"Message\"));\r\n");
		jsWriter.write("			}\r\n");
		jsWriter.write("			return getUploadedFileUrl(returnObj);\r\n");
		jsWriter.write("		} finally {\r\n");
		jsWriter.write("			try {\r\n");
		jsWriter.write("				channel.close();\r\n");
		jsWriter.write("			} catch (Exception e) {\r\n");
		jsWriter.write("			}\r\n");
		jsWriter.write("			try {\r\n");
		jsWriter.write("				fileChannel.close();\r\n");
		jsWriter.write("			} catch (Exception e) {\r\n");
		jsWriter.write("			}\r\n");
		jsWriter.write("			try {\r\n");
		jsWriter.write("				fis.close();\r\n");
		jsWriter.write("			} catch (Exception e) {\r\n");
		jsWriter.write("			}\r\n");
		jsWriter.write("		}\r\n");
		jsWriter.write("	}\r\n");
		jsWriter.write("\r\n");
		jsWriter.write("	private final static JSONObject post(int actionId, boolean asyncService, JSONObject data) throws Exception {\r\n");
		jsWriter.write("		JSONObject requestData = new JSONObject();\r\n");
		jsWriter.write("		requestData.put(\"ActionId\", actionId);\r\n");
		jsWriter.write("		requestData.put(\"UId\", getUID());\r\n");
		jsWriter.write("		requestData.put(\"AsyncService\", asyncService);\r\n");
		jsWriter.write("		requestData.put(\"RequestData\", data);\r\n");
		jsWriter.write("		String message = requestData.toString();\r\n");
		jsWriter.write("		message  = URLEncoder.encode(message, \"UTF-8\");\r\n");
		jsWriter.write("\r\n");
		jsWriter.write("		PrintWriter out = null;\r\n");
		jsWriter.write("		BufferedReader in = null;\r\n");
		jsWriter.write("		String result = \"\";\r\n");
		jsWriter.write("		try {\r\n");
		jsWriter.write("			URL realUrl = new URL(\"http://\"+_host+\":\"+_port+_webServer+\"/JsonRemote\");\r\n");
		jsWriter.write("			URLConnection conn = realUrl.openConnection();\r\n");
		jsWriter.write("			conn.setRequestProperty(\"accept\", \"*/*\");\r\n");
		jsWriter.write("			conn.setRequestProperty(\"connection\", \"Keep-Alive\");\r\n");
		jsWriter.write("			conn.setRequestProperty(\"user-agent\", \"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)\");\r\n");
		jsWriter.write("			conn.setDoOutput(true);\r\n");
		jsWriter.write("			conn.setDoInput(true);\r\n");
		jsWriter.write("			out = new PrintWriter(conn.getOutputStream());\r\n");
		jsWriter.write("			out.print(message);\r\n");
		jsWriter.write("			out.flush();\r\n");
		jsWriter.write("			in = new BufferedReader(new InputStreamReader(conn.getInputStream(),\"UTF-8\"));\r\n");
		jsWriter.write("			String line;\r\n");
		jsWriter.write("			while ((line = in.readLine()) != null) {\r\n");
		jsWriter.write("			    result += line;\r\n");
		jsWriter.write("			}\r\n");
		jsWriter.write("		} catch (Exception e) {\r\n");
		jsWriter.write("			System.out.println(\"发送 POST 请求出现异常！\"+e);\r\n");
		jsWriter.write("			e.printStackTrace();\r\n");
		jsWriter.write("		}\r\n");
		jsWriter.write("		finally{\r\n");
		jsWriter.write("			try{\r\n");
		jsWriter.write("				if(out!=null){\r\n");
		jsWriter.write("					out.close();\r\n");
		jsWriter.write("				}\r\n");				
		jsWriter.write("				if(in!=null){\r\n");
		jsWriter.write("					in.close();\r\n");			
		jsWriter.write("				}\r\n");			
		jsWriter.write("			}\r\n");			
		jsWriter.write("			catch(IOException ex){\r\n");
		jsWriter.write("				ex.printStackTrace();\r\n");
		jsWriter.write("			}\r\n");
		jsWriter.write("		}\r\n");
		jsWriter.write("		JSONObject returnObj = new JSONObject(result);\r\n");
		jsWriter.write("		if (!returnObj.getBoolean(\"IsOK\")) {\r\n");
		jsWriter.write("			throw new Exception(returnObj.getString(\"Message\"));\r\n");
		jsWriter.write("		}\r\n");
		jsWriter.write("		return returnObj;\r\n");
		jsWriter.write("	}\r\n");
		jsWriter.write("\r\n");
		jsWriter.write("	private static final List<int[]> getUpdateResult(JSONObject serviceResult) throws Exception {\r\n");
		jsWriter.write("		List<int[]> result = new ArrayList<int[]>();\r\n");
		jsWriter.write("		JSONArray jArray = serviceResult.getJSONArray(\"Result\");\r\n");
		jsWriter.write("		int row = jArray.length();\r\n");
		jsWriter.write("		for (int i = 0; i < row; i++) {\r\n");
		jsWriter.write("			JSONArray rowArray = jArray.getJSONArray(i);\r\n");
		jsWriter.write("			int col = rowArray.length();\r\n");
		jsWriter.write("			int[] colData = new int[col];\r\n");
		jsWriter.write("			for (int j = 0; j < col; j++) {\r\n");
		jsWriter.write("				colData[j] = rowArray.getInt(j);\r\n");
		jsWriter.write("			}\r\n");
		jsWriter.write("			result.add(colData);\r\n");
		jsWriter.write("		}\r\n");
		jsWriter.write("		return result;\r\n");
		jsWriter.write("	}\r\n");
		jsWriter.write("\r\n");
		jsWriter.write("	private static final String getUploadedFileUrl(JSONObject serviceResult) throws Exception {\r\n");
		jsWriter.write("		String fileUrl = null;\r\n");
		jsWriter.write("		JSONArray jArray = serviceResult.getJSONArray(\"FileUrl\");\r\n");
		jsWriter.write("		if (jArray.length() > 0) {\r\n");
		jsWriter.write("			fileUrl = jArray.getString(0);\r\n");
		jsWriter.write("		}\r\n");
		jsWriter.write("		return fileUrl;\r\n");
		jsWriter.write("	}\r\n");
		jsWriter.write("\r\n");
		
		jsWriter.flush();
	}
	public void write(String str)throws Exception{
		jsWriter.write(str);
		jsWriter.flush();
	}

	public void close() throws Exception {
		jsWriter.write("}\r\n");
		jsWriter.close();
	}

}
